var index = {
    color: ['rgb(68,114,196)', 'rgb(237,125,49)', 'rgb(165,165,165)', 'rgb(255,192,0)',
        'rgb(153,216,123)', "rgb(0,174,157)", 'rgb(101,194,148)', 'rgb(199,126,181)',
        'rgb(0,154,214)', 'rgb(175,180,219)', 'rgb(163,207,98)', 'rgb(37,133,166)', 'rgb(105,77,159)', 'rgb(243,145,169)'],
    county: ['全市', '白云区', '观山湖区', '花溪区', '开阳县', '南明区', '清镇市', '乌当区', '息烽县', '修文县', '云岩区'],
    compareTableHead: ['序号', '对比项目', '对比分值项'],//比对数据表头
    compareItemTableHead: ['问卷项目', '贵阳监测（百分比）', '教育部十二城市监测（百分比）', '教育部十二城市监测（百分比）'],//指标项目比对表头
    schoolTableHead: ['学段', '学校名称', '2019年', '2020年', '2021年', '对比'],//德育监测三年得分对比变化表头
    isShowSmallDataLabel: false,//是否现实数据标签
    isShowDataLabel: false,//是否显示echarts数据标签
    isExport: true,//是否可以导出
    isShowDataTable: true,//是否显示数据表格
    toolBoxShow: false,
    sampleAnalysisTitles: ['性别', '是否独生子女', '父母的文化程度', '家庭居住地',
        '是否是班干部', '与母亲居住在家里的时间', '与父亲居住在家里的时间', '民族',
        '学习成绩', '住宿状况', '学校类别', '学校性质', '学校所在地'],
    sampleAnalysisChartIds: ['sex', 'isSingleKid', 'parentDegree', 'jzAddress',
        'isStaff', 'liveWithFatherTime', 'liveWithMotherTime', 'ethnic',
        'academic', 'stay', 'schoolType', 'schoolNature', 'schoolAddress'],
    grade: ['五年级', '初二', '高二'],
    //获取差异series
    getDiffSeries: function (data, divId) {
        var series = [];
        var str = "<tr><th></th>";
        var xaxis = Object.getOwnPropertyNames(data['desc']);
        for (var i = 0; i < xaxis.length; i++) {
            str += "<th>" + xaxis[i] + "</th>";
        }
        str += "</tr>";
        var str2 = "";
        var desc = data['desc'];
        for (var obj in desc) {
            str2 += ' <p class="text-indent line-h-28">' + desc[obj] + '</p>';
        }
        var detail = data['data'];
        for (var obj in detail) {

            str += "<tr><td>" + obj + "</td>";
            var arr = detail[obj];
            for (var i = 0; i < arr.length; i++) {
                str += "<td>" + arr[i] + "</td>";
            }
            str += "</tr>";
            var temp = {
                name: obj,
                type: 'bar',
                data: detail[obj],
                label: {
                    normal: {
                        show: index.isShowSmallDataLabel,//开启显示
                        position: 'top',//柱形上方
                        textStyle: { //数值样式
                            color: '#02030a'
                        }
                    }
                }
            };
            series.push(temp);
        }
        $("#" + divId).next().html(str);//拼接表单
        $("#" + divId).next().next().html(str2);//拼接内容
        return series;
    },
    //echarts画图工具
    drawChart: function (divId, data) {
        var myChart = echarts.init(document.getElementById(divId));
        var option = {
            animation: false,
            color: index.color,
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: Object.getOwnPropertyNames(data['data']),
                top: 'bottom'
            },
            toolbox: {
                show: index.toolBoxShow,
                orient: 'vertical',
                right: 'right',
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            xAxis: [
                {
                    type: 'category',
                    axisTick: {show: false},
                    data: Object.getOwnPropertyNames(data['desc'])
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: index.getDiffSeries(data, divId)
        };
        myChart.setOption(option);
    },
    /**
     *@description 创建数据表格
     *@author XieXing
     * @param data 数据
     * @param xAxis 横坐标
     * @param tableClass 对应表格class
     *@date 2021/12/29 16:21
     */
    drawTable: function (data, xAxis, tableClass) {
        if (!index.isShowDataTable) {
            return false;
        }
        var str = "<tr><th>年份</th>";
        for (var i = 0; i < xAxis.length; i++) {
            str += ("<th>" + xAxis[i] + "</th>");
        }
        str += "</tr>";
        for (var obj in data) {
            str += "<tr><td>" + obj + "</td>";
            for (var i = 0; i < data[obj].length; i++) {
                str += ("<td>" + data[obj][i] + "</td>");
            }
            str += "</tr>";
        }
        $(tableClass).html(str);
    },
    /**
     *@description 学校数据详情
     *@author XieXing
     *@date 2022/1/7 14:36
     */
    drawSchoolTable: function (data, txtCla, txt, tableData, tableClass) {
        $(txtCla).text(data[txt]);//文本赋值
        var str = "<tr><th colspan='6'>德育监测三年得分对比变化</th></tr>";
        str += "<tr><th>学段</th><th>学校名称</th><th>2019年</th><th>2020年</th><th>2021年</th><th>对比</th></tr>";
        data = data[tableData];
        var primarySchools = data['primary'];
        str += "<tr><td rowspan='" + primarySchools.length + "'>小学</td>";
        for (var i = 0; i < primarySchools.length; i++) {
            if (i == 0) {
                str += "<td>" + primarySchools[i]['schoolName'] + "</td><td>" + primarySchools[i]['2019'] + "</td><td>" + primarySchools[i]['2020'] + "</td><td>" + primarySchools[i]['2021'] + "</td><td>" + primarySchools[i]['diff'] + "</td></tr>";
            } else {
                str += "<tr><td>" + primarySchools[i]['schoolName'] + "</td><td>" + primarySchools[i]['2019'] + "</td><td>" + primarySchools[i]['2020'] + "</td><td>" + primarySchools[i]['2021'] + "</td><td>" + primarySchools[i]['diff'] + "</td></tr>";
            }
        }

        var juniorSchools = data['junior'];
        str += "<tr><td rowspan='" + juniorSchools.length + "'>初中</td>";
        for (var i = 0; i < juniorSchools.length; i++) {
            if (i == 0) {
                str += "<td>" + juniorSchools[i]['schoolName'] + "</td><td>" + juniorSchools[i]['2019'] + "</td><td>" + juniorSchools[i]['2020'] + "</td><td>" + juniorSchools[i]['2021'] + "</td><td>" + juniorSchools[i]['diff'] + "</td></tr>";
            } else {
                str += "<tr><td>" + juniorSchools[i]['schoolName'] + "</td><td>" + juniorSchools[i]['2019'] + "</td><td>" + juniorSchools[i]['2020'] + "</td><td>" + juniorSchools[i]['2021'] + "</td><td>" + juniorSchools[i]['diff'] + "</td></tr>";
            }
        }

        var seniorSchools = data['senior'];
        str += "<tr><td rowspan='" + seniorSchools.length + "'>高中</td>";
        for (var i = 0; i < seniorSchools.length; i++) {
            if (i == 0) {
                str += "<td>" + seniorSchools[i]['schoolName'] + "</td><td>" + seniorSchools[i]['2019'] + "</td><td>" + seniorSchools[i]['2020'] + "</td><td>" + seniorSchools[i]['2021'] + "</td><td>" + seniorSchools[i]['diff'] + "</td></tr>";
            } else {
                str += "<tr><td>" + seniorSchools[i]['schoolName'] + "</td><td>" + seniorSchools[i]['2019'] + "</td><td>" + seniorSchools[i]['2020'] + "</td><td>" + seniorSchools[i]['2021'] + "</td><td>" + seniorSchools[i]['diff'] + "</td></tr>";
            }
        }

        $(tableClass).html(str);

    },
    //总体监测结果
    chart1: function (data) {
        index.drawSchoolTable(data, '.txt1', 'allSituationTxt', "allSituationScore", '.allSituationTable');
    },
    //获取样本分析legend
    getSampleAnalysis: function (data) {
        return Object.getOwnPropertyNames(data);
    },
    //获取样本分析图标series
    getSampleAnalysisSeries: function (data) {
        var series = [];
        for (var obj in data) {
            var temp = {
                name: obj,
                type: 'bar',
                data: data[obj],
                label: {
                    normal: {
                        show: index.isShowSmallDataLabel,//开启显示
                        position: 'top',//柱形上方
                        textStyle: { //数值样式
                            color: '#02030a'
                        }
                    }
                }
            };
            series.push(temp);
        }
        return series;
    },
    //画转置柱状图
    drawReverseChart: function (data, divId) {
        var myChart = echarts.init(document.getElementById(divId));
        var option = {
            animation: false,
            color: index.color,
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: index.getSampleAnalysis(data),
                top: 'bottom'
            },
            toolbox: {
                show: index.toolBoxShow,
                orient: 'vertical',
                right: 'right',
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
            },
            yAxis: {
                type: 'category',
                data: index.grade
            },
            series: index.getSampleAnalysisSeries(data)
        };
        myChart.setOption(option);
    },
    //描绘样本分析表格
    drawSampleAnalysisTable: function (data, tabCla) {
        var str = "<tr><th></th><th>五年级</th><th>初二</th><th>高二</th></tr>";
        for (var obj in data) {
            str += "<tr><td>" + obj + "</td>";
            var temp = data[obj];
            for (var i = 0; i < temp.length; i++) {
                str += "<td>" + temp[i] + "</td>";
            }
            str += "</tr>";
        }
        $(tabCla).html(str);
    },
    //描绘学校样本
    drawSampleAnalysis: function (data, sampleCla) {
        var sampleData = data['sampleData'];
        for (var i = 0; i < index.sampleAnalysisTitles.length; i++) {
            var str = '<p class="f-14 f-family-1 f-weight ">2.' + (i + 1) + '.' + index.sampleAnalysisTitles[i] + '</p>\n' +
                '                    <p class="text-indent line-h-28"></p>\n' +
                '                    <div id="' + index.sampleAnalysisChartIds[i] + '" class="chart reverse-chart"></div>\n' +
                '                    <table class="' + index.sampleAnalysisChartIds[i] + 'Table table-bordered reverse-table">\n' +
                '\n' +
                '                    </table>';
            $(sampleCla).append(str);
            var txt = sampleData[i]['txt'];//文本内容
            $("#" + index.sampleAnalysisChartIds[i]).prev().text(txt);
            var txtData = sampleData[i]['data'];//数据内容
            index.drawReverseChart(txtData, index.sampleAnalysisChartIds[i]);
            index.drawSampleAnalysisTable(txtData, "." + index.sampleAnalysisChartIds[i] + "Table");
        }
    },
    //各学段表格
    drawXdTable: function (data, tabCla) {
        var str = "<tr><th colspan='2'>德育监测总体得分</th></tr><tr><th>学校（市、区）</th><th>小学德育总分</th></tr>";
        for (var i = 0; i < data.length; i++) {
            str += "<tr><td>" + data[i]['schoolName'] + "</td><td>" + data[i]['score'] + "</td></tr>";
        }
        $(tabCla).html(str);
    },

    //描绘差异
    drawDiff: function (data, xd) {
        index.drawChart(xd + "UrDiff", data[xd + 'UrDiff']);//城乡差异
        index.drawChart(xd + "SexDiff", data[xd + 'SexDiff']);//性别差异
        index.drawChart(xd + "SingleChildDiff", data[xd + 'SingleChildDiff']);//独生子女差异
        index.drawChart(xd + "AchievementDiff", data[xd + 'AchievementDiff']);//成绩差异
    },
    //描绘检测内容
    drawTestContent: function (data, xd) {
        var testContent = data[xd + 'TestContent'];
        for (var i = 0; i < testContent.length; i++) {
            var obj = testContent[i];
            var str = ' <p class="text-indent line-h-28">\n' +
                '                            <label>' + obj["index"] + '</label><span>' + obj["content"] + '</span></p>\n' +
                '                        <div id="' + xd + 'TestContent' + i + '" class="chart">\n' +
                '\n' +
                '                        </div>\n' +
                '                        <table class="' + xd + 'TestContentTable' + i + ' table-bordered">\n' +
                '\n' +
                '                        </table>\n' +
                '                        <p class="text-indent line-h-28"><span>' + obj["detail"] + '</span></p>\n' +
                '                    ';
            $('.' + xd + '-test-content').append(str);
            index.drawChart('', '', xd + 'TestContent' + i, obj, 'score');
            index.drawTable(obj['score'], index.county, '.' + xd + 'TestContentTable' + i);
        }
    },
    //描绘比对表格
    drawCompareTable: function (data, xd) {
        var str = "<tr>";
        var head = index.compareTableHead.concat(index.county);
        for (var i = 0; i < head.length; i++) {
            str += "<th>" + head[i] + "</th>";
        }
        str += "</tr>";
        for (var i = 0; i < data.length; i++) {
            var obj = data[i];
            var preYearData = obj['2020'];
            str += "<tr><td rowspan='3'>" + (i + 1) + "</td><td rowspan='3'>" + obj['index'] + "</td><td>2020年</td>";
            for (var t = 0; t < preYearData.length; t++) {
                str += "<td>" + preYearData[t] + "</td>";
            }
            str += "</tr>";
            var curYearData = obj['2021'];
            str += "<tr><td>2021年</td>";
            for (var t = 0; t < curYearData.length; t++) {
                str += "<td>" + curYearData[t] + "</td>";
            }
            str += "</tr>";
            var compareData = obj['diff'];
            str += "<tr><td>波动值</td>";
            for (var t = 0; t < compareData.length; t++) {
                if (compareData[t] < 0) {
                    str += "<td class='red'>" + compareData[t] + "</td>";
                } else {
                    str += "<td class='blue'>" + compareData[t] + "</td>";
                }
            }
            str += "</tr>";
        }
        $("." + xd + "CompareTable").html(str);
    },
    //描绘指标对比
    drawItemTable: function (data, xd) {
        var str = "<tr>";
        for (var i = 0; i < index.compareItemTableHead.length; i++) {
            str += "<th>" + index.compareItemTableHead[i] + "</th>";
        }
        str += "</tr>";
        for (var i = 0; i < data.length; i++) {
            var obj = data[i];
            str += "<tr><td>" + obj['item'] + "</td><td>" + obj['gy'] + "</td><td>" + obj['edu'] + "</td><td>" + obj['coastalCity'] + "</td></tr>";
        }
        $("." + xd + "ItemTable").html(str);
    },

    //相关性描绘
    drawRelevant: function (data, xd) {
        $("." + xd + "RelevantSummary").text(data[xd + "Relevant"]['summary']);
        var items = data[xd + "Relevant"]['item'];
        var str = "";
        for (var i = 0; i < items.length; i++) {
            str += '<p class="text-indent line-h-28">（' + (i + 1) + ')' + items[i] + '</p>';
        }
        $("." + xd + "RelevantItem").html(str);
    },
    //描绘指标
    drawIndexes: function (data, xd, num) {
        var indexStr = "";
        for (var i = 0; i < data.length; i++) {
            var curIndex = data[i];
            indexStr += "<p class='f-12 f-family-1 f-weight '>" + num + ".3." + (i + 1) + "." + curIndex['name'] + "</p> <p class='f-16 f-family-1 f-weight '>"+ num + ".3." + (i + 1) + "." + "1.监测情况</p><p class='text-indent line-h-28'>" + curIndex['situation']['content'] + "</p>";
            var situationTableHead = curIndex['situation']['tableHead'];
            indexStr += ' <table>\n' +
                '                        <tr>\n' +
                '                            <th>学校（市、区）</th>';
            for (var j = 0; j < situationTableHead.length; j++) {
                indexStr += "<th>" + situationTableHead[j] + "</th>";
            }
            indexStr += "</tr>";
            var situationTableData = curIndex['situation']['data'];
            for (var obj in situationTableData) {
                indexStr += "<tr><td>" + obj + "</td>";
                var curSituationData = situationTableData[obj];
                for (var m = 0; m < curSituationData.length; m++) {
                    indexStr += "<td>" + curSituationData[m] + "</td>";
                }
                indexStr += "</tr>";
            }
            indexStr += "</table>";
            indexStr += ' <p class="f-12 f-family-1 f-weight ">'+ num + '.3.' + (i + 1) + '.' + '2.答题情况分析</p>';
            var analysis = curIndex['analysis'];
            for (var n = 0; n < analysis.length; n++) {
                indexStr += ' <p class="text-indent line-h-28">' + analysis[n] + '</p>';
            }
            indexStr += "<table>\n" +
                "                        <tr>\n" +
                "                            <th>题目内容</th>\n" +
                "                            <th>题目类型</th>\n" +
                "                            <th>指标名称</th>\n" +
                "                            <th>市（区县）平均分</th>\n" +
                "                            <th>赞同/符合/正确人数占比</th>\n" +
                "                            <th>反对/不符合/错误人数占比</th>\n" +
                "                        </tr>";
            var questions = curIndex['questions'];
            for (var obj in questions) {
                indexStr += "<tr><td>" + obj + "</td>";
                var questionData = questions[obj];
                for (var m = 0; m < questionData.length; m++) {
                    indexStr += "<td>" + questionData[m] + "</td>";
                }
                indexStr += "</tr>";
            }
            indexStr += "</table>";
        }
        $("." + xd + "IndexSituation").html(indexStr);
    },
    appendXdHtml: function (xd, num) {
        var str = '<p class="f-14 f-family-1 f-weight ">' + num + '.1.总体情况</p>\n' +
            '                    <p class="text-indent line-h-28 ' + xd + 'AllSituationTxt"></p>\n' +
            '                    <table class="' + xd + 'AllSituationScore"></table>' +
            '                    <p class="f-14 f-family-1 f-weight ">' + num + '.2.差异对比分析</p>\n' +
            '                    <p class="f-16 f-family-1 f-weight ">' + num + '.2.1.城乡差异</p>\n' +
            '                    <div id="' + xd + 'UrDiff" class="chart"></div>\n' +
            '                    <table class="reverse-table"></table>\n' +
            '                    <div></div>\n' +
            '                    <p class="f-16 f-family-1 f-weight ">' + num + '.2.2.性别差异</p>\n' +
            '                    <div id="' + xd + 'SexDiff" class="chart reverse-chart"></div>\n' +
            '                    <table class="reverse-table"></table>\n' +
            '                    <div></div>\n' +
            '                    <p class="f-16 f-family-1 f-weight ">' + num + '.2.3.独生子女差异</p>\n' +
            '                    <div id="' + xd + 'SingleChildDiff" class="chart reverse-chart"></div>\n' +
            '                    <table class="reverse-table"></table>\n' +
            '                    <div></div>\n' +
            '                    <p class="f-16 f-family-1 f-weight ">' + num + '.2.4.成绩差异</p>\n' +
            '                    <div id="' + xd + 'AchievementDiff" class="chart"></div>\n' +
            '                    <table class="reverse-table"></table>\n' +
            '                    <div></div>\n' +
            '                    <p class="f-14 f-family-1 f-weight ">' + num + '.3.指标答题情况</p>\n' +
            '                    <div class="' + xd + 'IndexSituation"></div>';
        $("." + xd + "-container").html(str);
    },
    //刻画学段
    drawXd: function (data, xd, num) {
        index.appendXdHtml(xd, num);
        $("." + xd + "AllSituationTxt").text(data[xd + 'AllSituationTxt']);
        index.drawXdTable(data[xd + 'AllSituationScore'], "." + xd + "AllSituationScore");
        index.drawDiff(data, xd);
        index.drawIndexes(data[xd + 'Indexes'], xd, num);
    },
    canvas2Img: function (claObject) {
        //将第一个画布作为基准。
        var baseCanvas = $(claObject).find("canvas").first()[0];
        if (!baseCanvas) {
            return false;
        }
        var width = baseCanvas.width;
        var height = baseCanvas.height;
        var ctx = baseCanvas.getContext("2d");
        //遍历，将后续的画布添加到在第一个上
        $(claObject).find("canvas").each(function (i, canvasObj) {
            if (i > 0) {
                var canvasTmp = $(canvasObj)[0];
                ctx.drawImage(canvasTmp, 0, 0, width, height);
            }
        });
        //获取base64位的url
        var base64Str = baseCanvas.toDataURL();
        $(claObject).html("<img src=" + base64Str + " alt='图片不存在'> ");
        return baseCanvas.toDataURL();
    },
    init2: function () {
        if (!index.isExport) {
            return false;
        }
        var echarts = $('.chart');
        for (var i = 0; i < echarts.length; i++) {
            index.canvas2Img(echarts[i]);
        }
    },
    init: function (areaName, sysCode) {
        $.get("/dyReportCountyData/getData", {areaName: areaName, sysCode: sysCode}, function (data) {
        // $.get("/static/json/moral_education/county/county_report_" + areaName + ".json", {}, function (data) {
            $(".studentNumber").text(data['studentNumber']);
            $(".primaryStudentNumber").text(data['primaryStudentNumber']);
            $(".juniorStudentNumber").text(data['juniorStudentNumber']);
            $(".seniorStudentNumber").text(data['seniorStudentNumber']);
            index.chart1(data);
            index.drawSampleAnalysis(data, '.sample-container');
            index.drawXd(data, 'primary', 3.1);
            index.drawXd(data, 'junior', 3.2);
            index.drawXd(data, 'senior', 3.3);
            $(".scoreLevel").text(data['txt']);
            index.init2();
        });
    }
};